#include <QDebug>
#include <QGraphicsView>
#include <QGraphicsSceneWheelEvent>
#include "trafficscene.h"

TrafficScene::TrafficScene( QObject *parent, QGraphicsView *view)
  : QGraphicsScene(parent)
{
  setView(view);
}

TrafficScene::~TrafficScene()
{
}

void TrafficScene::setView(QGraphicsView *view)
{
  mView = view;
}

void TrafficScene::wheelEvent( QGraphicsSceneWheelEvent *wheelEvent )
{
  if (mView)
  {
    // Some fancy math to get the mouseWheel scroll/pan to work the way it does.
    // I should probably 'splain this a little at some point...
    float panSpeedLimiter = 50.0;
    QPointF sceneCenter = mView->mapToScene(mView->rect().center());
    QPointF windowCenterDelta = wheelEvent->screenPos() - (mView->mapToGlobal(mView->rect().center()));

    // Cap panning so the screen edge doesn't send us flying off into nowhere
    if (windowCenterDelta.x() > panSpeedLimiter)
      windowCenterDelta.setX(panSpeedLimiter);
    else if (windowCenterDelta.x() < -panSpeedLimiter)
      windowCenterDelta.setX(-panSpeedLimiter);
    if (windowCenterDelta.y() > panSpeedLimiter)
      windowCenterDelta.setY(panSpeedLimiter);
    else if (windowCenterDelta.y() < -panSpeedLimiter)
      windowCenterDelta.setY(-panSpeedLimiter);

    float horizontalScale = windowCenterDelta.x() / (mView->width()/2);
    float verticalScale = windowCenterDelta.y() / (mView->height()/2);
    float newX = (wheelEvent->scenePos().x() - sceneCenter.x()) * qAbs(horizontalScale);
    float newY = (wheelEvent->scenePos().y() - sceneCenter.y()) * qAbs(verticalScale);

    //qDebug() << "SCENE: delta=" << wheelEvent->delta() << "sreenp=" << wheelEvent->screenPos() << "scenep=" << wheelEvent->scenePos();

    // Determine new center to pan the map as we zoom
    QPointF newCenter((sceneCenter.x() + newX), (sceneCenter.y() + newY));

    // Apply pan and zoom
    if (wheelEvent->delta() > 0)
      mView->scale(1.2, 1.2);
    else
      mView->scale(1/1.2, 1/1.2);
    mView->centerOn(newCenter);
  }

  // Suppresses vert/horiz scrolling
  wheelEvent->accept();
}
